package arcane.object.gui.scroll;

import java.awt.Color;
import java.awt.Graphics2D;
import java.util.List;
import java.util.Vector;

import arcane.constant.Constants;
import arcane.object.game.sprite.MenuSprite;

import com.golden.gamedev.object.GameFont;

public class ListModel<T> extends MenuSprite {
	protected List<T> model;
	private int selectedIndex;
	private int difference;
	protected int visibleY, visibleX;
	protected GameFont font;

	Color bgColor;

	public ListModel() {
		this(null, 0, 0);
	}

	public ListModel(List<T> items, int x, int y) {
		super(x, y);
		model = new Vector<T>();
		visibleX = 0;
		visibleY = 0;
		selectedIndex = -1;
		font = Constants.fontManager.getFont("MenuFont");
		if (items != null) {
			model.addAll(items);
		}
		width = 200;
		height = 400;
		bgColor = Constants.PURPLE;
	}

	public void add(T t) {
		model.add(t);
	}

	public List<T> getData() {
		return model;
	}

	public void setData(List<T> data) {
		model = data;
	}

	public boolean remove(T t) {
		return model.remove(t);
	}
	
	public T remove(int index){
		return model.remove(index);
	}

	public void clear() {
		model.clear();
	}

	public int size() {
		return model.size();
	}

	/**
	 * Mouse was clicked somewhere within this component
	 * 
	 * @param x
	 *            x location of mouse button
	 * @param y
	 *            y location of mouse button
	 */
	public void mouseClicked(int x, int y) {
		int h = font.getHeight() + 2;
		int selected = (visibleY + y - (int) getY()) / h;
		if (selected >= model.size()) {
			selected = model.size() - 1;
		}
		this.selectedIndex = selected;
	}

	protected int calculateVerticalArea() {
		int h = font.getHeight() + 2;
		h *= model.size();
		return h;
	}

	public void render(Graphics2D g, int x, int y) {
		int h = font.getHeight() + 2;
		int y2 = y;
		g.setColor(bgColor);
		g.fillRect(x, y, getWidth(), getHeight());
		setOpenGLColor(color);
		int startIndex = visibleY != 0 ? (int) ((double)visibleY
				/ (calculateVerticalArea()/h)) : 0;
		difference = visibleY - startIndex * h;
		 //System.out.println("VisibleY: " + visibleY + " i = " + startIndex
		 //+ " size=" + model.size() + " va = " + calculateVerticalArea());
		g.setClip(x, y, width, height);
		for (int i = startIndex; i < model.size(); i++) {
			if (i == selectedIndex) {
				g.setColor(Color.WHITE);
				g.fillRect(x, y2 - difference, width, h - 2);
			}
			font.drawString(g, model.get(i).toString(), x, y2 - difference);
			y2 += h;
		}
		if (getBorder() != null) {
			this.getBorder().paintBorder(this, g);
		}
		g.setClip(0, 0, 640, 480);
	}
}